package com.threefire.quickstart;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;

/**
 * @author zhouyanxiang
 * @Date 2021-01-2021/1/9-23:45
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * channelActive
     * 激活方法
     * @param cx ChannelHandlerContext对象
     */
    @Override
    public void channelActive(ChannelHandlerContext cx) {
        System.err.println("Server Channel active...");
    }

    /**
     *
     */
    @Override
    public void channelRead(ChannelHandlerContext cx, Object msg) throws UnsupportedEncodingException {
        // 1.读取客户端的数据（缓存中去取并打印到控制台）
        ByteBuf buf = (ByteBuf) msg;
        byte[] request = new byte[buf.readableBytes()];
        buf.readBytes(request);
        String requestBody = new String(request,"utf-8");
        System.err.println("Server " + requestBody);

        // 2.返回相应数据
        String responseBody = "返回响应数据" + requestBody;
        cx.writeAndFlush(Unpooled.copiedBuffer(responseBody.getBytes()));

    }

    /**
     * 捕获异常方法
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
        ctx.fireExceptionCaught(throwable);
    }

}
